const path = require('path')
const fs = require('fs')
const dayjs = require('dayjs')
const xlsx = require('xlsx')
const { columnExcelMap, excelColumnMap } = require('./column-map')
// const { Realtime } = require('../models')
const { History } = require('../models')

function getFile(reader, upStream) {
  return new Promise(function (result) {
    let stream = reader.pipe(upStream) // 可读流通过管道写入可写流
    stream.on('finish', function (err) {
      result(err)
    })
  })
}

module.exports = {
  uploadExcel: async (ctx) => {
    const file = ctx.request.files.file // 获取上传文件
    const reader = fs.createReadStream(file.path) // 创建可读流
    const ext = file.name.split('.').pop() // 获取上传文件扩展名
    const fileName = dayjs().format('YYYYMMDDHHmmss') + '.' + ext
    const savePath = path.resolve(__dirname, `../uploadExcels/${fileName}`)
    const upStream = fs.createWriteStream(savePath) // 创建可写流

    const nowStr = dayjs().format('YYYY-MM-DD HH:mm:ss')

    try {
      await getFile(reader, upStream) // 等待数据存储完成
      const workbook = xlsx.readFile(savePath)
      let json = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
      if (json && json.length) {
        json = json.map((item) => {
          const newItem = {}
          for (const [itemKey, itemValue] of Object.entries(item)) {
            const newKey = excelColumnMap[itemKey]
            newItem[newKey] = '' + itemValue // 这里将一些整数都转换成字符串
            // if (itemValue.length > 10) {
            //   console.log('xxxx', newKey, itemValue)
            // }
          }
          // console.log(newItem)
          newItem.createAt = nowStr
          return newItem
        })
      }
      await importToHistory(json)

      ctx.body = {
        code: 200,
        data: json,
        msg: '上传成功'
      }
    } catch (error) {
      console.log('导入excel出错：', error)
      ctx.body = {
        code: 500,
        data: null,
        msg: '数据导入不成功'
      }
    }
  }
}

async function importToHistory(data) {
  try {
    let bulkData = []
    if (Array.isArray(data)) {
      // 如果传递过来的是数组
      for (d of data) {
        const [history, created] = await History.findOrCreate({
          where: { code: d.code },
          defaults: { ...d }
        })
        console.log(created)
      }
    } else {
      // 如果是对象
      const [history, created] = await History.findOrCreate({
        where: { code: data.code },
        defaults: { ...data }
      })
      console.log(created)
    }
  } catch (error) {
    console.log('将数据导入到表中时出错', error)
  }
}
